package com.fcy.teamwork.base

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.fcy.teamwork.App
import com.fcy.teamwork.repo.RetrofitClient
import com.fcy.teamwork.security.environment.EnvironmentSec
import java.util.*

fun BaseActivity<out ViewBinding>.toActivity(
    clazz: Class<out AppCompatActivity>,
) {
    val intent = Intent(this, clazz)
    startActivity(intent)
}


private const val TAG = "Ext"
fun log(msg: Any?) {
//    if (EnvironmentSec.isDebug)
        Log.d(TAG, "log: ${msg.toString()}")
}

fun View.closeKeyboard() {
    val imm: InputMethodManager =
        context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Context.toast(msg: String) {
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}

val colors = arrayOf(
    0xFEeea2a4,
    0xFEed5a65,
    0xFEd2568c,
    0xFEc08eaf,
    0xFE2474b5,
    0xFEdc9123
)

fun generateColor(): Int {
    val position = Random().nextInt(colors.size)
    return colors[position].toInt()
}

val scale = App.application.resources.displayMetrics.density.toInt()
fun Int.toPx(): Int = this * scale
fun Int.toDp(): Int = this / scale
val gson by lazy { RetrofitClient.gson }
fun Any.toJson(): String =
    gson.toJson(this)

inline fun <reified T> String.fromJson(): T = gson.fromJson(this, T::class.java)

fun View.noFastCLick(internal: Long = 500, action: () -> Unit) {
    setOnClickListener(object : OnClickListener {
        var lastTime = -1L
        override fun onClick(v: View?) {
            if ((lastTime == -1L) || ((System.currentTimeMillis() - lastTime) > internal)) {
                lastTime = System.currentTimeMillis()
                action()
            }
        }
    })
}